require([ 'jquery', 'common', 'validate','timepicker', 'pagination', 'bootstrap', 'dateZh','plupload','T_upload'], function($, common,validate,timepicker,T_upload) {
	
	//日期控件
	$('#date-start, #date-end').datetimepicker({
		format : "yyyy-mm-dd hh:ii:ss",
		language : "zh-CN",
		todayBtn : 1,
		autoclose : true,
		todayHighlight : true,
		forceParse : true,
		minuteStep : 60
	});
	 
	
	var first_load = true;
	var reload = true; 
	
	//placeholder兼容ie start
	$(function() {
		if (!placeholderSupport()) { // 判断浏览器是否支持 placeholder
			$('[placeholder]').focus(function() {
				var input = $(this);
				if (input.val() == input.attr('placeholder')) {
					input.val('');
					input.removeClass('placeholder');
				}
			}).blur(function() {
				var input = $(this);
				if (input.val() == ''
						|| input.val() == input.attr('placeholder')) {
					input.addClass('placeholder');
					input.val(input.attr('placeholder'));
				}
			}).blur();
		};
		
		showByPage(1); 
	});
	function placeholderSupport() {
		return 'placeholder' in document.createElement('input');
	}
	//placeholder兼容ie end

	//清除按钮
	$('.clearBtn').on('click', function() {
		$('.setTableLength').val(10); 
		$("#id").val('');
		$("select[name='confirmedStatus']").val('');
		$("select[name='transferStatus']").val('');
		$("#date-start").val('');
		$("#date-end").val('')
	});
	
	$(".setTableLength").change(function() {
		reload = true;
		showByPage(1);
	});

	$(".searchBtn").click(function() {
		reload = true;
		showByPage(1);
	});
	
	/** 列表查询start **/
	function showByPage(pageNum) {
		if ($(".all").is(':checked')) {
			$(".all").removeAttr('checked');								
		}	
		if($('.alert-warning').length>0){
    		$('.alert-warning').remove();
    	}
		$.getJSON(ctx + '/bill/showbypage', {	
				pageNum : pageNum,
				pageSize : $('.setTableLength').val() || 10, 
				id : $("#id").val(), 
				confirmedStatus : $("select[name='confirmedStatus']").val(), 
				transferStatus : $("select[name='transferStatus']").val(),
				startTime : $("#date-start").val(),
				endTime : $("#date-end").val(),
				supplierName : $("input[name='supplierName']").val()
			},
			function(data){  
				if($('.loading')){
					$('.loading').remove();
				}
				var result = data.result;
				if(result!=null && result=="noauthority") {
					common.alert1('你无此权限!');
					return;
				}
				if(data.result!=null && data.result=="againLogin") {
					common.alert1("登录过期，请重新登录");
						setTimeout("location.href = ctx + '/login.html'",1000);
       			} else if(data.result.length == 0) { 
					$('.table-responsive').append('<div class="alert alert-warning no-result text-center" role="alert">没有找到记录 </div>');
                } else{
                	var isInterior = $("#isInterior").val();
       				var datapage = data.result;
					var datalist = datapage.result;
					var totalCount = datapage.totalCount;
					var pageNum = datapage.pageNo;
					var pageSize = datapage.pageSize;
					var totalPages = datapage.totalPages;
					$(".totalCount").html(totalCount);
					$(".totalPages").html(totalPages);
					$(".pageNo").html(pageNum);
                    var tempHtml="";   
                    var ser = 1;
                    for(var i=0;i<datalist.length;i++){   
                    	var list = datalist[i]; 
                    	var no = (pageNum-1)*pageSize+i+1; 
                    	tempHtml +="<tr data-id='"+list.id+"' data-pageno='" + pageNum + "'>"; 
                    	tempHtml +="<td>"+ser+"</td>"; 
                    	tempHtml +="<td>"+isnull(list.supplierName)+"</td>"; 
                    	tempHtml +="<td>"+cart(list.bankAccount)+"</td>";
                    	tempHtml +="<td>"+isnull(list.bankName)+"</td>";
                    	tempHtml +="<td>"+isnull(list.contactsName)+"</td>";
                    	tempHtml +="<td>"+settlementType(list.settlementType)+"</td>";
                    	tempHtml +="<td>"+isnull(list.id)+"</td>";
                    	tempHtml +="<td>"+common.getSmpFormatDate(list.createTime)+"</td>"; 
                    	
                    	if(isInterior == 1){
                    		tempHtml +="<td>"+isnull(list.orderAmount.toFixed(2))+"</td>";
                    	}
                    	
                    	
                    	tempHtml +="<td>"+list.billAmount.toFixed(2)+"</td>"; 
                    	tempHtml +="<td>-"+isnull(list.refundAmount.toFixed(2))+"</td>";
                    	tempHtml +="<td>"+isnull(list.freight.toFixed(2))+"</td>";
                    	tempHtml +="<td>"+isnull(list.taxAmount.toFixed(2))+"</td>";
                    	
                    	tempHtml +="<td>"+list.otherAmount.toFixed(2)+"</td>";
                    	/*tempHtml +="<td>"+list.adjustAmount.toFixed(2)+"</td>";*/
                    	tempHtml +="<td>"+list.settlementAmount.toFixed(2)+"</td>";
                    	tempHtml +="<td>"+confirmedStatus(list.confirmedStatus)+"</td>";
                    	tempHtml +="<td>"+transferStatus(list.transferStatus)+"</td>"; 
                    	tempHtml +="<td class='noExl'>";
                    	tempHtml +="<button type='button' data-toggle='modal' data-target='.modal-billdetail' data-id="+list.id+" class='btn btn-primary btn-xs detail-btn'>明细</button>&nbsp;";
                    	
                    	if(list.confirmedStatus == 1 && isInterior == 0) {
                    		//供应商确认账单是否有误 
                    		tempHtml +="<button type='button' data-toggle='modal' data-target='.modal-edityd' data-id="+list.id+" class='btn btn-warning btn-xs audit-this'>确认</button>&nbsp;"; 
                    	} 
                    	
                    	if(isInterior == 1){
                    		//供应商确认状态，1等待确认，2账单无误，3账单有误
                    		if(list.confirmedStatus == 2 && list.transferStatus == 1) {
                        		tempHtml +="<button type='button' data-id="+list.id+" class='btn btn-success btn-xs transfer-this'>转账</button>&nbsp;"; 
                        	}
                    	} 
                    	
                    	tempHtml +="</td>";
                    	ser = ser + 1;
                    	tempHtml +="</tr>";
                    	if($('.alert-warning').length>0){
                    		$('.alert-warning').remove();
                    	}
                    }   
                    if(datalist.length === 0&&$('.alert-warning').length<=0) { 
						$('.table-responsive').append('<div class="alert alert-warning no-result text-center" role="alert">没有找到记录 </div>');
	                } 
                    $('#dataBody').html(tempHtml);
                   
                    if (reload) {
                    	reload = false;
                    	first_load = true;
    					var initPagination = function() {
    						$("#Pagination").pagination(totalCount, {
    							num_edge_entries : 1, // 边缘页数
    							num_display_entries : 4, // 主体页数
    							callback: pageselectCallback,
    							prev_text : "«",
    							next_text : "»",
    							items_per_page : pageSize, 
    							link_to : 'javascript:void(0);'
    						});
    					}();
    					/**分页e**/
                    }
				} 
			}).fail(function (err) { 
				if($('.loading')){
					$('.loading').remove();
				}
				common.alert('服务器错误！请刷新页面重试或联系管理员',"确定"); 
            });  
	}
	
	function pageselectCallback(page_index, jq) {
		if (first_load) { //第一次初始化不需要请求
			first_load = false;
			return false;
		}
		pageNum = page_index + 1;
		showByPage(pageNum);
	}
	/** 列表查询end **/
	
	/**删除多个s*/
	$('#transferMany').click(function(e) {
		var ids = "";
		var count = 0;
		var checks = document.getElementsByName("itemCheck");
		console.log(checks);
		for(var i=0;i<checks.length;i++){
			if(checks[i].checked){
				count++;
				ids += checks[i].value + ",";
			}
		}
		if(count<1){
			common.alert1("请至少选择一个");
		}else{
			$('.commonConfirm').modal('show');
			common.commonConfirm("删除", "确定删除", "这"+count+"个吗",
				function() {
	            	 $.post(ctx+"/logistics/deletebyids", {ids:ids},
	            		function (data) {
		            		 var result = data.result;
		     				 if(result!=null && result=="noauthority") {
		     					 common.alert1('你无此权限!');
		     					 return;
		     				 }
	    		    		 if(data.result!=null && data.result=="againLogin") {
	    		    			 $('.commonConfirm').modal('hide');
	    		    			 common.alert1("登录过期，请重新登录");
	    						 setTimeout("location.href = ctx + '/login.html'",1000);
	    		             }else if(data.result=='success'){ 
	    		         		 $(".commonConfirm").modal('hide');
	    		     	         common.mySuccessModal2(data.message);
	    		     	        showLogisticsByPage(1);
	    		         	}else{
	    		         		$(".updateMsg").html(data.message);
	    		         	}
	    		 },"json"); 
			});
		}
	});
	/**删除多个e*/
	
	/** 供应商确认账单无误start **/
	$("#btn_audit_pass").click(function() { 
		//供应商确认状态，1等待确认，2账单无误，3账单有误
		audit(2); 
	});
	/**  供应商确认账单无误end **/

	/** 账单有误start **/
	$("#btn_audit_notpass").click(function() { 
//		供应商确认状态，1等待确认，2账单无误，3账单有误
		audit(3);
	});
	/**  账单有误end **/
		
	function audit(auditStatus) {
		var id = $("#auditDetailForm").find("input[name='id']").val(); 
		$.post(ctx+"/bill/confirm", {
				id:id,
				status:auditStatus
		},function (data) {
			var result = data.result;
			if(result!=null && result=="noauthority") {
				common.alert1('你无此权限!');
				return;
			}
			 if(result!=null && result=="againLogin") {
				 $('.commonConfirm').modal('hide');
				 common.alert1("登录过期，请重新登录");;
				 setTimeout("location.href = ctx + '/login.html'",1000);
		     }else if(result=='success'){  
		    	 $('.modal-edityd').modal('hide');
		    	 $('.commonConfirm').modal('hide'); 
		         common.mySuccessModal2('提交成功');
		         showByPage(1);
		  	}else{
		  		$(".errorMsg").html(data.message);
		  	}
		  },"json"); 
	}
	
	/**操作已转账start */
	$(document).on('click', '.transfer-this', function(){
		var varId = $(this).data("id");
		var parentTr = $(this).parents('tr');
        var pageno = parentTr.data('pageno');
		$('.commonConfirm').modal('show');				
		common.commonConfirm("转账", "确定已转账", "",
			function() {
            	 $.post(ctx+"/bill/transfer", {
    				 id:varId
    			 },function (data) {
    				 var result = data.result;
					 if(result!=null && result=="noauthority") {
						 common.alert1('你无此权限!');
						 return;
					 }
    	    		 if(data.result!=null && data.result=="againLogin") {
    	    			 $('.commonConfirm').modal('hide');
    	    			 common.alert1("登录过期，请重新登录");
    					 setTimeout("location.href = ctx + '/login.html'",1000);
    	             }else if(data.result=='success'){ 
    	            	$('.commonConfirm').modal('hide');
    	     	        common.mySuccessModal2(data.message);
    	     	       showByPage(pageno);
    	         	}else{
    	         		common.alert1(data.message);
    	         	}
    	         },"json"); 
			}
		);
	});
	/** 操作已转账end **/
	
	$(document).on('click', '.audit-this', function (e) { 
        var $this = $(this),
        parentTr = $this.parents('tr'),
        id = $this.data('id'),
        pageno = parentTr.data('pageno');
    	$.getJSON(ctx + '/bill/detail', {
    		id : id
    	}, function(data) {
    		var result = data.result;
			if(result!=null && result=="noauthority") {
				common.alert1('你无此权限!');
				return;
			}
    		if(data==null || data.length <= 0){
    			$(".updateMsg").html("数据异常,请重试");
    		}else{
    			var bill = data.bill; 
    			var orderList = data.orderList;
    			$("#auditDetailForm").find("input[name='id']").val(bill.id);
    			$('#auditDetailForm').find("input[name='supplierName']").val(bill.supplierName);
    			$('#auditDetailForm').find("select[name='settlementType']").val(settlementType(bill.settlementType)); 
    			$('#auditDetailForm').find("input[name='createTime']").val(common.getSmpFormatDate(bill.createTime));
    			$('#auditDetailForm').find("input[name='billAmount']").val(bill.billAmount.toFixed(2));
    			$('#auditDetailForm').find("input[name='refundAmount']").val(bill.refundAmount.toFixed(2));
    			$('#auditDetailForm').find("input[name='freight']").val(bill.freight.toFixed(2)); 
    			$('#auditDetailForm').find("input[name='taxAmount']").val(bill.taxAmount.toFixed(2));
    			$('#auditDetailForm').find("input[name='otherAmount']").val(bill.otherAmount.toFixed(2));
    			$('#auditDetailForm').find("input[name='adjustAmount']").val(bill.adjustAmount.toFixed(2));
    			$('#auditDetailForm').find("input[name='settlementAmount']").val(bill.settlementAmount.toFixed(2));
    			$('#auditDetailForm').find("select[name='confirmedStatus']").val(bill.confirmedStatus);
    			$('#auditDetailForm').find("select[name='transferStatus']").val(bill.transferStatus);
    			var tempHtml = "";
    			for(var i=0;i<orderList.length;i++){
    				var order = orderList[i]; 
    				tempHtml +="<tr>";  
    				tempHtml +="<td>"+isnull(order.orderId)+"</td>";  
                	tempHtml +="<td>"+order.receiver+"</td>"; 
                	tempHtml +="<td>"+order.receiverMobile+"</td>";
                	tempHtml +="<td>"+common.getSmpFormatDate(order.deliveryTime)+"</td>";
                	tempHtml +="<td>"+isnull(order.logisticsName)+"</td>";
                	tempHtml +="<td>"+isnull(order.logisticsNumber)+"</td>";
                	tempHtml +="<td>"+common.getSmpFormatDate(order.createTime)+"</td>";
                	tempHtml +="<td>"+common.getSmpFormatDate(order.paymentTime)+"</td>";
                	tempHtml +="<td>"+order.freight.toFixed(2)+"</td>"; 
                	tempHtml +="<td>"+order.refundAmount.toFixed(2)+"</td>"; 
                	tempHtml +="<td>"+order.taxAmount.toFixed(2)+"</td>"; 
                	tempHtml +="</tr>";
    			}
    			$('#orderBillDetailDataBody').html(tempHtml);
    		}
    	});
    });
	
	//查看明细
	$(document).on('click', '.detail-btn', function (e) { 
        var $this = $(this),
        parentTr = $this.parents('tr'),
        id = $this.data('id'),
        pageno = parentTr.data('pageno');
    	$.getJSON(ctx + '/bill/detail', {
    		id : id
    	}, function(data) {
    		var result = data.result;
			if(result!=null && result=="noauthority") {
				common.alert1('你无此权限!');
				return;
			}
    		if(data==null || data.length <= 0){
    			$(".updateMsg").html("数据异常,请重试");
    		}else{
    			var bill = data.bill; 
    			var isInterior = $("#isInterior").val(); 
    			var tempHtml = "";
    			var orderList = data.orderList;
    			for(var i=0;i<orderList.length;i++){
    				var order = orderList[i]; 
    				var orderProduct = order.orderProductList;
    				if(orderProduct!= null && orderProduct.length>0) {
    					var totalProductUnitPrice = 0;	//商品成本总价（不含税）
    					for(var j=0;j<orderProduct.length;j++){
    						var op = orderProduct[j]; 
    						tempHtml +="<tr id='trd_"+order.id+"'>";  
    	                	tempHtml +="<td>"+isnull(order.orderId)+"</td>"; 
    	                	if(isInterior == 1) {
    	                		tempHtml +="<td>--</td>";
    	                	}
    	                	tempHtml +="<td>"+isnull(order.status)+"</td>"; 
    	                	tempHtml +="<td>"+order.supplierId+"</td>"; 
    	                	tempHtml +="<td>"+common.getSmpFormatDate(order.paymentTime)+"</td>"; 
    	                	tempHtml +="<td>"+common.getSmpFormatDate(order.deliveryTime)+"</td>";
    	                	tempHtml +="<td>--</td>";
    	                	tempHtml +="<td>"+isnull(order.logisticsName)+"</td>";
    	                	tempHtml +="<td>"+isnull(order.logisticsNumber)+"</td>";
    						
    	                	tempHtml +='<td>'+op.code+'</td>';
                    		tempHtml +='<td>'+op.productName+'</td>';
                    		tempHtml +='<td>'+op.num+'</td>';
                    		if(isInterior == 1) {
                        		tempHtml +="<td>"+order.orderAmount.toFixed(2)+"</td>"; 
                        	} 
                    		tempHtml +="<td>"+op.unitPrice.toFixed(2)+"</td>";
                    		tempHtml +="<td>"+(op.specificationNumber*op.unitPrice).toFixed(2)+"</td>";
                    		tempHtml +="<td>"+order.freight.toFixed(2)+"</td>"; 
                        	tempHtml +="<td>"+order.taxAmount.toFixed(2)+"</td>";  
                        	
                        	totalProductUnitPrice = op.specificationNumber * op.unitPrice;
                        	//结算总金额
                        	var billAmount = parseFloat(totalProductUnitPrice) + parseFloat(order.freight) + parseFloat(order.taxAmount);
                        	tempHtml +="<td>"+ billAmount.toFixed(2) +"</td>";   
                        	tempHtml +="<td>"+order.settlementBillId+"</td>"; 
                        	tempHtml +="</tr>"; 
    					}
    				}  
//                	
//                	if(orderProduct!= null && orderProduct.length>0) {
//                		var op = orderProduct[0];
//                		totalProductUnitPrice = orderProduct[i].specificationNumber*orderProduct[i].unitPrice;
//                		tempHtml +='<td>'+orderProduct[i].code+'</td>';
//                		tempHtml +='<td>'+orderProduct[i].productName+'</td>';
//                		tempHtml +='<td>'+orderProduct[i].num+'</td>';
//                		if(isInterior == 1) {
//                    		tempHtml +="<td>"+order.orderAmount.toFixed(2)+"</td>"; 
//                    	} 
//                		tempHtml +="<td>"+orderProduct[i].unitPrice.toFixed(2)+"</td>";
//                		tempHtml +="<td>"+(orderProduct[i].specificationNumber*orderProduct[i].unitPrice).toFixed(2)+"</td>";
//                	}else{
//                		tempHtml +='<td></td>';
//                		tempHtml +='<td></td>';
//                		tempHtml +='<td></td>';
//                		if(isInterior == 1) {
//                    		tempHtml +="<td>"+order.orderAmount.toFixed(2)+"</td>"; 
//                    	} 
//                		tempHtml +="<td></td>";
//                		tempHtml +="<td></td>";
//                	}
//                	tempHtml +="<td>"+order.freight.toFixed(2)+"</td>"; 
//                	tempHtml +="<td>"+order.taxAmount.toFixed(2)+"</td>";  
//                	//结算总金额
//                	var billAmount = parseFloat(totalProductUnitPrice) + parseFloat(order.freight) + parseFloat(order.taxAmount);
//                	tempHtml +="<td>"+ billAmount.toFixed(2) +"</td>";   
//                	tempHtml +="<td>"+order.settlementBillId+"</td>"; 
//                	tempHtml +="</tr>";  
    			}
    			$('#billDetailDataBody').html(tempHtml);
    		}
    	});
    });
	
	//查看订单的商品
	$(document).on('click', '.product-detail-btn', function (e) { 
        var $this = $(this),
        parentTr = $this.parents('tr'),
        id = $this.data('id') 
        if($("tr").hasClass("product-detail-"+id)) {
        	$(".product-detail-"+id).remove();
        	return;
        }
    	$.getJSON(ctx + '/bill/order/product', {
    		id : id
    	}, function(data) {
    		var result = data.result;
			if(result!=null && result=="noauthority") {
				common.alert1('你无此权限!');
				return;
			}
    		if(data==null || data.length <= 0){
    			$(".updateMsg").html("数据异常,请重试");
    		}else{ 
    			var tboty=[];
                tboty.push("<tr class='product-detail-"+id+"' style='text-align: center;' >");
                tboty.push('<th></th>');
                tboty.push('<th style="text-align: center;" >商品货号</th>');
                tboty.push('<th style="text-align: center;" colspan=3>商品名称</th>');
                tboty.push('<th style="text-align: center;" >效期</th>');
                tboty.push('<th style="text-align: center;" >商品规格数量</th>');
                tboty.push('<th style="text-align: center;" >购买数量</th>');
                tboty.push('<th  style="text-align: center;" colspan=2>商品成本单价（不含税）</th>');
                tboty.push('<th colspan=2>商品成本总价（不含税）</th>'); 
                for(var i=0;i<data.length;i++){ 
                    tboty.push("<tr class='product-detail-"+id+"'>");
                    tboty.push('<td></td>');
                    tboty.push('<td>'+data[i].code+'</td>');
                    tboty.push('<td colspan=3>'+data[i].productName+'</td>');
                    tboty.push('<td>'+data[i].dateValue+'</td>');
                    tboty.push("<td>"+data[i].specificationNumber+data[i].packType+"装</td>");
                    tboty.push('<td>'+data[i].num+'</td>')
                    tboty.push("<td colspan=2>"+data[i].price+"</td>");
                    tboty.push("<td colspan=2>"+(data[i].specificationNumber*data[i].price).toFixed(2)+"</td>"); 
                }
                $("#trd_"+id).after(tboty.join(''));  
    		}
    	});
    });
	
	function isnull(value) {
		if (value == null || value == '' || typeof (value) == "undefined")
			return "--";
		else
			return value;
	}

	/*对账状态，1等待确认，2账单无误，3账单有误*/
	function confirmedStatus(value) {
		if (value == null || value == ''){
			return "未知";
		}else if(value == 1) {
			return "等待确认";
		}else if(value == 2) {
			return "账单无误";
		}else if(value == 3) {
			return "<span style='color:red'>账单有误</span>";
		}  
	}
	
	//结算周期，1当日结算，2周结、3十日结、4月结
	function settlementType(value) {
		if (value == null || value == ''){
			return "未知";
		}else if(value == 1) {
			return "当日结算";
		}else if(value == 2) {
			return "周结";
		}else if(value == 3) {
			return "十日结";
		}else if(value == 4) {
			return "月结";
		} 
	}
	
	function cart(val) {
		if(val == null || val == '') {
			return "--";
		}
		return val.replace(/[\s]/g, '').replace(/(\d{4})(?=\d)/g, "$1 ");
	}
	
	
	/*转账状态，1待转账，2已转账，3未转账，4转账失败*/
	function transferStatus(value) {
		if (value == null || value == ''){
			return "未知";
		}else if(value == 1) {
			return "<span style='color:red'>待转账</span>";
		}else if(value == 2) {
			return "已转账";
		}else if(value == 3) {
			return "未转账";
		} else if(value == 4) {
			return "转账失败";
		}  
	} 
	
	function isnumber(value) {
		if (value == null || value == '')
			return "0.00";
		else
			return value;
	}
	
});